<?php

namespace App\Http\Middleware;

use Closure;
use App\Constant\BackendApiConstant;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class KnyPermissionMideleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next,$permission)
    {
        $uid = Auth::id();
        
        $permission = DB::table('users_roles AS ur')
            ->leftJoin('role AS r', 'ur.rid', '=', 'r.rid')
            ->leftJoin('role_permission AS rp', 'rp.rid', '=', 'r.rid')
            ->select([
                'rp.permission AS permission',
            ])
            ->where('ur.uid',$uid)
            ->where('rp.permission', $permission)
            ->first();
        if(!empty($permission)){
            return $next($request);
        }else{
            return response()->json([
                'code' => 403,
                'message' => '缺少权限，无法访问。',
            ]);
        }
    }
}
